package pew.pong;

import com.jme3.app.SimpleApplication;
import com.jme3.network.Client;
import com.jme3.network.ClientStateListener;
import com.jme3.network.Network;
import com.jme3.network.serializing.Serializer;
import com.jme3.renderer.RenderManager;
import com.jme3.system.JmeContext;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import pew.pong.network.message.ShutdownServerMessage;

/**
 * test
 * @author normenhansen
 */
public class PongControlClient extends SimpleApplication implements ClientStateListener {

    public static void main(String[] args) {
	String host = "localhost";
	int port = 6143;
	
	if (args.length > 0) {
	    host = args[0];
	}
	if (args.length > 1) {
	    port = Integer.parseInt(args[1]);
	}
	
        PongControlClient app = new PongControlClient(host, port);
        app.start(JmeContext.Type.Headless);
    }
    private Client client;
    private final int port;
    private final String host;

    private PongControlClient(String host, int port) {
	this.host = host;
	this.port = port;
    }

    @Override
    public void simpleInitApp() {
        try {
	    Serializer.registerClass(ShutdownServerMessage.class);
            
            client = Network.connectToServer(host, port);
	    client.addClientStateListener(this);
            client.start();
        } catch (IOException ex) {
            Logger.getLogger(PongControlClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void simpleUpdate(float tpf) {
        //TODO: add update code
    }

    @Override
    public void simpleRender(RenderManager rm) {
        //TODO: add render code
    }

    @Override
    public void destroy() {
	if (client.isConnected()) {
	    client.close();
	}
        super.destroy();
    }

    public void clientConnected(Client c) {
	Logger.getLogger("PongLog").info("--- Connected to server!");
	ShutdownServerMessage m = new ShutdownServerMessage();
	client.send(m);
    }

    public void clientDisconnected(Client c, DisconnectInfo info) {
	Logger.getLogger("PongLog").info("--- Disconnected from server! " + info.reason);
	stop();
    }
}
